package com.jl15988.simpletools.appcore.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.jl15988.simpletools.appcore.constant.AppConstant;
import com.jl15988.simpletools.appcore.constant.AuditConstant;
import com.jl15988.simpletools.appcore.dto.AuditDTO;
import com.jl15988.simpletools.appcore.dto.AuditQueryDTO;
import com.jl15988.simpletools.appcore.dto.AuditRequestDTO;
import com.jl15988.simpletools.appcore.entity.App;
import com.jl15988.simpletools.appcore.entity.Audit;
import com.jl15988.simpletools.appcore.mapper.AppMapper;
import com.jl15988.simpletools.appcore.mapper.AuditMapper;
import com.jl15988.simpletools.appcore.service.AuditService;
import com.jl15988.simpletools.common.exception.BusinessException;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;

/**
 * 审核服务实现类
 *
 * @author jl15988
 */
@Service
public class AuditServiceImpl extends ServiceImpl<AuditMapper, Audit> implements AuditService {

    @Autowired
    private AuditMapper auditMapper;

    @Autowired
    private AppMapper appMapper;

    @Override
    public IPage<AuditDTO> getAuditPage(AuditQueryDTO query) {
        Page<Audit> page = new Page<>(query.getPageNum(), query.getPageSize());
        IPage<Audit> auditPage = auditMapper.selectAuditPage(page, query);
        
        // 转换为DTO
        return auditPage.convert(this::convertToDTO);
    }

    @Override
    public AuditDTO getLatestAudit(Long appId) {
        // 检查应用是否存在
        App app = appMapper.selectById(appId);
        if (app == null) {
            throw new BusinessException("应用不存在");
        }
        
        Audit audit = auditMapper.selectLatestByAppId(appId);
        if (audit == null) {
            return null;
        }
        
        AuditDTO dto = convertToDTO(audit);
        dto.setAppIcon(app.getIcon());
        dto.setAppVersion(app.getVersion());
        
        return dto;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public Long submitAudit(AuditRequestDTO request, Long auditorId, String auditorName) {
        // 检查应用是否存在
        App app = appMapper.selectById(request.getAppId());
        if (app == null) {
            throw new BusinessException("应用不存在");
        }
        
        // 检查应用状态是否为待审核
        if (app.getStatus() != AppConstant.STATUS_PENDING) {
            throw new BusinessException("只能审核待审核状态的应用");
        }
        
        // 创建审核记录
        Audit audit = new Audit();
        audit.setAppId(request.getAppId());
        audit.setAppName(app.getName());
        audit.setStatus(request.getStatus());
        audit.setComment(request.getComment());
        audit.setAuditorId(auditorId);
        audit.setAuditorName(auditorName);
        audit.setCreatedAt(LocalDateTime.now());
        audit.setUpdatedAt(LocalDateTime.now());
        
        auditMapper.insert(audit);
        
        // 更新应用状态
        if (request.getStatus() == AuditConstant.STATUS_APPROVED) {
            // 审核通过，更新应用状态为已发布
            app.setStatus(AppConstant.STATUS_PUBLISHED);
        } else if (request.getStatus() == AuditConstant.STATUS_REJECTED) {
            // 审核拒绝，应用状态保持待审核
            // 开发者需要修改后重新提交
        }
        app.setUpdatedAt(LocalDateTime.now());
        appMapper.updateById(app);
        
        return audit.getId();
    }

    @Override
    public Long getPendingAuditCount() {
        LambdaQueryWrapper<App> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(App::getStatus, AppConstant.STATUS_PENDING);
        return appMapper.selectCount(wrapper);
    }

    @Override
    public Long getDeveloperPendingAuditCount(Long developerId) {
        LambdaQueryWrapper<App> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(App::getStatus, AppConstant.STATUS_PENDING)
                .eq(App::getDeveloperId, developerId);
        return appMapper.selectCount(wrapper);
    }

    /**
     * 将实体转换为DTO
     *
     * @param audit 审核实体
     * @return 审核DTO
     */
    private AuditDTO convertToDTO(Audit audit) {
        AuditDTO dto = new AuditDTO();
        BeanUtils.copyProperties(audit, dto);
        return dto;
    }
} 